package com.snap.awesomeserial.model;

import android.os.Environment;

import com.snap.awesomeserial.AppConfig;
import com.snap.awesomeserial.bean.TemplateInfo;
import com.snap.awesomeserial.utils.FileUtils;

import java.io.File;


/**
 * 文件Mgr
 * 总体流程分2个步骤
 * 序列化：   bean --> proto stuff --> Gzip压缩后写入文件
 * 反序列化   文件经Gzip解压后字节流读出  -->  proto stuff  --> bean
 */
public class FileManager {

    private static final String TAG = "FileManager";

    private FileManager() {
    }

    private static class FileManagerHolder {
        private static final FileManager manager = new FileManager();
    }

    public static FileManager getInstance() {
        return FileManagerHolder.manager;
    }

    /**
     * 将template bean存入文件
     */
    public boolean saveTempData(TemplateInfo templateInfo) {
        if (templateInfo == null) return false;
        byte[] byteArray = FileUtils.serialize(templateInfo);
        File file = new File(getTempFilePath(templateInfo.getName()));
        FileUtils.mkFile(file);
        return FileUtils.writeFile(file, byteArray);
    }


    /**
     * 从文件中读取出 template bean
     */
    public TemplateInfo getTempDataByName(String fileName) {
        String path = getTempFilePath(fileName);
        File file = new File(path);
        if (!file.exists()) return null;
        byte[] byteArray = FileUtils.readFile(file);
        if (byteArray == null) return null;
        return FileUtils.deserialize(byteArray, TemplateInfo.class);
    }

    public boolean removeTempData(String fileName) {
        String path = getTempFilePath(fileName);
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            return file.delete();
        }
        return false;
    }

    public String getTempFilePath(String fileName) {
        return Environment.getExternalStorageDirectory().getPath() + AppConfig.TEMPLATE_DIRECTORY + fileName + ".temp";
    }

    public String getExcelFilePath(String fileName) {
        return Environment.getExternalStorageDirectory().getPath() + AppConfig.EXCEL_DIRECTORY + fileName + ".xls";
    }
}
